package org.fin.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.fin.exception.PersistenceFrameworkException;
import org.fin.pojo.MappedStatement;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.fin.pojo.MappedStatement.Type.*;

public class MapperStatementBuilder {

  @SuppressWarnings("unchecked")
  public  Map<String, MappedStatement> parse(InputStream in) throws DocumentException {

    Document doc = new SAXReader().read(in);

    Element root = doc.getRootElement();
    List<Element> nodeList = new ArrayList<>();
    nodeList.addAll(root.selectNodes("//select"));
    nodeList.addAll(root.selectNodes("//update"));
    nodeList.addAll(root.selectNodes("//insert"));
    nodeList.addAll(root.selectNodes("//delete"));
    String namespace = root.attributeValue("namespace");


    Map<String, MappedStatement> statementsMap = new HashMap<>();
    for (Element element : nodeList) {
      String id = element.attributeValue("id");
      String resultType = element.attributeValue("resultType");
      String paramterType = element.attributeValue("parameterType");
      String sql = element.getTextTrim();
      MappedStatement.Type type = getType(element.getName());


      MappedStatement statement = new MappedStatement();
      statement.setId(id);
      statement.setResultType(resultType);
      statement.setParamterType(paramterType);
      statement.setSql(sql);
      statement.setType(type);

      String statementId = namespace + "." + id;
      statementsMap.put(statementId, statement);
    }

    return statementsMap;
  }

  private MappedStatement.Type getType(String name) {
    switch (name) {
      case "select":
        return SELECT;
      case "insert":
        return INSERT;
      case "update":
        return UPDATE;
      case "delete":
        return DELETE;
      default:
        throw new PersistenceFrameworkException("未知标签: " + name);
    }
  }

}
